package net.lsr.demo.server;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * desc: 应用服务器
 * @author lsr
 * @version 2014年5月21日
 */
@Controller
public class AppServer {
	private static final Logger logger = LoggerFactory.getLogger(AppServer.class);
	
	// 平台验证时用
	@RequestMapping(value="/back", method = RequestMethod.GET, produces="text/plain")
	@ResponseBody
	public String checkServerUrl(HttpServletRequest request){
		String signature = request.getParameter("signature");// 加密签名,就是token
		String timestamp = request.getParameter("timestamp");// 时间戳
		String nonce = request.getParameter("nonce");// 随机数
		String echostr = request.getParameter("echostr");// 随机字符串
		
		logger.info("[timestamp:{}||signature:{}||nonce:{}||echostr:{}]", 
				new Object[]{timestamp, signature, nonce, echostr});
		
		if(isRequestValid(signature, timestamp, nonce, echostr))
			return echostr;// 验证通过则返回随机字符串
		else
			return "error";// 验证不通过，我们随便返回一个错误字符串，这里我们返回一个error
	}
	
	// 平台推送消息
	@RequestMapping(value="/back", method = RequestMethod.POST, produces="text/plain")
	@ResponseBody
	public String receiveMessage(HttpServletRequest request, @RequestParam("msg") String  msg){
		String signature = request.getParameter("signature");// 加密签名,就是token
		String timestamp = request.getParameter("timestamp");// 时间戳
		String nonce = request.getParameter("nonce");// 随机数
		String echostr = request.getParameter("echostr");// 随机字符串
		
		logger.info("app server received header:[timestamp:{}||signature:{}||nonce:{}||echostr:{}]", 
				new Object[]{timestamp, signature, nonce, echostr});
		 
		if(!isRequestValid(signature, timestamp, nonce, echostr))
			return "error";// 验证不通过，我们随便返回一个错误字符串，这里我们返回一个error
			
		// 处理接收到的信息
		logger.info("app server received msg :[{}]", msg);
		
		return "success";
	}

	private boolean isRequestValid(String signature, String timestamp, String nonce, String echostr) {
		return true;
	}
}
